﻿using Newtonsoft.Json.Linq;
using ShanghaiMetroAPP.Helper;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Shapes;

namespace ShanghaiMetroAPP.MetroDraw
{
    public enum StationState
    {
        normal,
        backstage
    }
    public class Station
    {
        private int STATION_SIZE = 15;
        private Vector2 _position = Vector2.zero;
        private string _name = string.Empty;
        private Color _color;
        private int _font_size;
        private bool _text_bold;
        private Vector2 _offset = Vector2.zero;
        private int[] _line_no;

        private Vector2 _shape_position;
        private Vector2 _text_position;
        private TextBlock _text_block;
        private Shape _shape;

        public int[] LineNo
        {
            get => _line_no;
            set
            {
                _line_no = value;
            }
        }

        public Vector2 Offset
        {
            get => _offset;
            set
            {
                _offset = value;
            }
        }

        public int FontSize
        {
            get => _font_size;
            set
            {
                _font_size = value;
            }
        }
        public bool TextBold
        {
            get => _text_bold;
            set
            {
                _text_bold = value;
            }
        }

        public Vector2 Position
        {
            get => _position;
            set
            {
                _position = value;
                //把图形位置改为和新坐标一致
                _shape_position = value;// * 2000;
                //Canvas绘图坐标的方向与笛卡尔坐标系是相反的

            }
        }
        public string Name
        {
            get => _name;
            set
            {
                _name = value;
            }
        }

        public Color Color
        {
            get => _color;
            set
            {
                _color = value;
            }
        }
        public StationState StationState
        {
            get => _station_state;
            set
            {
                if(_station_state == StationState.backstage)
                {

                }
                else if(_station_state == StationState.normal)
                {
                    
                }
            }
        }
        public string EnName { get; set; }
        public string PinyinName { get; set; }
        public Vector2 ShapePosition => _shape_position;
        public Vector2 TextPosition => _text_position;
        public string StationID { get; private set; }
        public string StationCode => StationID.Substring(2);
        private StationState _station_state;
        private MainWindow window;
        #region Static Method
        /// <summary>
        /// Debug模式下加载所有站点
        /// </summary>
        /// <returns></returns>
        public static List<Station> LoadStations(MainWindow window)
        {
            //重写了这个方法，车站和车站位置的坐标用新的配置文件读取
            //var json = File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + "TestingData\\StationInfo.json");
            //var obj = JObject.Parse(json);
            //var array = obj["levels"][0]["locations"].Value<JArray>();

            var array = JArray.Parse(File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + "TestingData\\StationInfoNew.json"));

            var stations = new List<Station>();
            foreach (var element in array)
            {
                double x = 0, y = 0;
                Vector2 offset = default;
                x = element["x"].Value<double>();
                y = element["y"].Value<double>();
                offset = new Vector2(element["text_x"].Value<double>(), element["text_y"].Value<double>());
                //var x = element["x"].Value<double>();
                //var y = element["y"].Value<double>();
                if (x != 0 && y != 0)
                {
                    var station = new Station(new Vector2(x, y), element["title"].Value<string>(), Colors.Red, window);
                    station.StationID = element["id"].Value<string>();
                    station.window = window;
                    station.Offset = offset;
                    station.PinyinName = element["pinyin"].Value<string>();
                    station.EnName = element["en_name"].Value<string>();
                    if (element["font_size"] != null)
                    {
                        station.FontSize = element["font_size"].Value<int>();
                        station.TextBold = element["text_bold"].Value<bool>();
                        //var offset = element["offset"];
                        //station.Offset = new Vector2(offset["x"].Value<double>(), offset["y"].Value<double>());
                        station.LineNo = element["line"].ToObject<int[]>();
                    }
                    stations.Add(station);
                }
            }
            return stations;
        }
        #endregion

        public Station(Vector2 pos, string name, Color color, MainWindow window)
        {
            this.Position = pos;
            this.Name = name;
            this.Color = color;
        }
        public Shape ToShape()
        {
            if (_shape == null)
            {
                _shape = new Ellipse();
                if (LineNo != null && LineNo.Length > 0 && Line.GetInstance(LineNo[0]) != null)
                {
                    //如果有指定线路号，且该线路号有配置，则指定为配置中的颜色
                    //对于线路来说，可能有多个线路号，则指定第一个元素为主要颜色。
                    _shape.Stroke = new SolidColorBrush(Line.GetInstance(LineNo[0]).Color);
                }
                else
                {
                    _shape.Stroke = new SolidColorBrush(Color);
                }
                _shape.StrokeThickness = 2;
                if (LineNo != null && LineNo.Length > 1)
                {
                    _shape.Width = 2*STATION_SIZE;
                    _shape.Height = 2*STATION_SIZE;
                }
                else
                {
                    _shape.Width = STATION_SIZE;
                    _shape.Height = STATION_SIZE;
                }

                //处理居中
                _shape_position -= new Vector2(_shape.Width, _shape.Height) * 0.5f;

                _shape.Cursor = Cursors.Hand;
                _shape.Fill = new SolidColorBrush(Colors.White);
                _shape.MouseEnter += (s, ex) =>
                {
                    //通知ViewModel
                    window.ViewModel.UpdateLineInfoList(StationCode);
                };
                Canvas.SetLeft(_shape, ShapePosition.x);
                Canvas.SetTop(_shape, ShapePosition.y);
            }
            return _shape;
        }

        public TextBlock ToText()
        {
            if (_text_block == null)
            {
                _text_block = new TextBlock();
                _text_block.FontSize = 18;
                _text_block.Text = Name;

                //if (Offset.length != 0)
                //{
                //    //y轴保持不变
                //    _text_position = _shape_position;
                //    //如果偏移量不为0，则偏移指定量
                //    _text_position += Offset;
                //}
                //else
                //{
                //    //否则设置为上部居中
                //    //上移20个像素
                //    _text_position = _shape_position + Vector2.up * -1 * 20;
                //}
                //修改为直接取值
                _text_position = Offset;
                //获取文字宽度
                //var size = GetMeasureString(Name, _text_block);
                ////左移文字宽度的一半(居中)
                //_text_position = TextPosition + Vector2.left * size.x * 0.5;
                ////右移站点宽度的一半
                //_text_position = TextPosition + Vector2.right * STATION_SIZE * 0.5;
                if (LineNo != null && LineNo.Length > 0 && Line.GetInstance(LineNo[0]) != null)
                {
                    //如果有指定线路号，且该线路号有配置，则指定为配置中的颜色
                    //对于线路来说，可能有多个线路号，则指定第一个元素为主要颜色。
                    _text_block.Foreground = new SolidColorBrush(Line.GetInstance(LineNo[0]).Color);
                }
                else
                {
                    _text_block.Foreground = new SolidColorBrush(Color);
                }
                Console.WriteLine(_text_block.ActualWidth);
                Canvas.SetLeft(_text_block, TextPosition.x);
                Canvas.SetTop(_text_block, TextPosition.y);
            }
            return _text_block;
        }
        private Vector2 GetMeasureString(string text, TextBlock tb)
        {
            var formattedText = new FormattedText(
                text,
                CultureInfo.CurrentCulture,
                FlowDirection.LeftToRight,
                new Typeface(tb.FontFamily, tb.FontStyle, tb.FontWeight, tb.FontStretch),
                tb.FontSize,
                Brushes.Black,
                new NumberSubstitution()
                );
            return new Vector2(formattedText.Width, formattedText.Height);
        }

        public override string ToString() => Name;
    }
}
